/*
* This file is the main code of Texdi
* Copyright (C) <2022>  <alkeon> [alkeon@autistici.org]
   
* Texdi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Texdi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Texdi.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <string>
#include <iostream>
#include <fstream>
#include "subprojects/tedi2lang/tedi2lang.h"
#include "subprojects/tedi2html/tedi2html.h"
#include "subprojects/tedi2tex/tedi2tex.h"
#include "subprojects/tedi2md/tedi2md.h"
#include "subprojects/tedi2ad/tedi2ad.h"
#include "preprocessor.h"
#include "exception.h"

#define HTML 1
#define LATEX 2
#define MD 3
#define AD 4

using namespace std;

/*
 * Generate latex header
 * author_s : author name
 * input : filename input file
 *
 * input will be the name of the document
 *
 */
string latex_header(string author_s, const string& input);
/*
 * clean_stdin()
 *  clean keyboard buffer
 */
void clean_stdin();
/*
 * Print --help option info.
 *
 */
void help_info();
/*
 * 
 * get html styles
 *
 */
string get_styles();

int main(int argc, char* argv[]) {

	int num = 0;
	string input;
	string output;
	string author_s;
	string header, end;
	int i = 1;
	bool help = false, has_wfile = false, has_rfile = false;
	bool embed_html_styles = true;
	while(i < argc && !help) {
		string arg(argv[i]);
		if(arg == "--help") {
			help_info();
			help = true;
		} else if(arg == "--latex") {
			num = LATEX;
			author_s = "0";

		} else if(arg == "--html")
			num = HTML;

		else if(arg == "--asciidoc")
			num = AD;

		else if(arg == "--markdown")
			num = MD;

		else if(arg == "--own-styles")
		  	embed_html_styles = false;

		else if(arg == "--header-file") {
			if(i + 1 < argc) {
				ifstream header_file(string(argv[++i]));
				string line;
				while(getline(header_file, line)){
					header += line + "\n";
				}
			} else
				cout << "--header-file option requires one argument." << endl;
		} else if(arg == "--end-file") {
			if(i + 1 < argc) {
				ifstream end_file(string(argv[++i]));
				string line;
				while(getline(end_file, line)){
					end += line + "\n";
				}
			} else
				cout << "--end-file option requires one argument." << endl;
		} else if(arg == "-o" or arg == "--output") {
			if(i + 1 < argc) {
				output = string(argv[++i]);
				has_wfile = true;
			} else
				cout << "--output option requires one argument." << endl;
			
		} else if(arg.find(".te") != string::npos) {
			has_rfile = true;
			input = string(argv[i]);
			output = input.substr(0, input.length() - 3);
		}
		++i;
	}
	if(!help) {
		if(!has_rfile) {
			cout << "Write filename" << endl;
			char char_input[100];
			cin.getline(char_input,100);
			input = string(char_input);
			if(!has_wfile)
				output = input.substr(0, input.length() - 3);
			clean_stdin();
		}
		while(num < 1 or num > 4) {
			cout << "Which format do yo want?" << endl;
			cout << "1.- HTML" << endl;
			cout << "2.- TEX" << endl;
			cout << "3.- MD" << endl;
			cout << "4.- AD" << endl;
			cin >> num;
		}
		try {
			string full_text = one_file(input);
			if(test_file(full_text)){
				switch(num){
					case HTML: {
						if(!has_wfile)
							output += ".html";

						if(header.size() == 0){
							header = "<!DOCTYPE html>\n\n"
							  "<!-- Done with Texdi -->\n\n "
							  "<head>\n";
							if(embed_html_styles)
								header += get_styles();

							header += "\n\t<link type=\"text/css\""
								" rel=\"stylesheet\" href=\"styles.css\">\n"
							  	"\t<meta charset=\"utf-8\">\n</head>\n<body>";
						}

						if(end.size() == 0)
							end = "\n</body>\n</html>";
						string text(tedi2html().convert(full_text, header, end));
						ofstream writer(output);
						writer << text;
						writer.close();

					};break;
					case LATEX: {
						if(!has_wfile)
							output += ".tex";

						if(header.size() == 0)
							header = latex_header(author_s,input);

						if(end.size() == 0)
							end = "\\end{document}";
						tedi2tex t2t;
						string text(t2t.convert(full_text, header, end));
						ofstream writer(output);
						writer << text;
						writer.close();
					};break;
					case MD: {
						if(!has_wfile)
							output += ".md";

						if(header.size() == 0)
							header = "<!-- Texdi ---> ";

						string text = tedi2md().convert(full_text, header, end);
						ofstream writer(output);
						writer << text;
						writer.close();
				
					};break;
					case AD:{
						if(!has_wfile)
							output += ".txt";
						string text = tedi2ad().convert(full_text, header, end);
						ofstream writer(output);
						writer << text;
						writer.close();

					};break;
					default: cout << "Wrong format chosed" << endl;
				}
			} else
				cout << "Conversion failed" << endl;
			
		}catch(Invalid i){
			cout << i.reason() << endl;
			cout << i.line() << endl;
		}
	}
}


string latex_header(string author_s, const string& input){

	string header = "\\documentclass[11pt,a4paper]{article}\n"
	  "\\usepackage[utf8]{inputenc}\n";

	cout << "Language used in the document" << endl;
	cout << "1.- Spanish" << endl;
	cout << "2.- Other" << endl;
	char char_input[2];
	clean_stdin();
	cin.getline(char_input, 2);

	if(char_input[0]=='1') 
		header += "\\usepackage[spanish]{babel}\n";

	header += "\\usepackage{hyperref}\n"
	  "\\usepackage{verbatim}\n\\usepackage{graphicx}\n"
	  "\\usepackage{underscore}\n\\usepackage[protrusion = true,final]"
	  "{microtype}\n\\setlength{\\emergencystretch}{10pt}\n"
	  "\\hypersetup{pageanchor=false}\n"
	  "\\title{"+input.substr(0,input.length()-3)+"}\n\\date{}";

	if(author_s!="0"){
		char author[100];
		cout << "Write author if you don't want an author use 0"<<endl;
		cin.getline(author,100);
		if(author[0] != '0'){
			author_s=string(author);
			header+="\n\\author{"+author_s+"}";
		}
	}

	header+="\n\\setlength\\parindent{0pt}\n\\begin{document}\n"
	  "\\maketitle\n\\newpage\n\\thispagestyle{empty}\n"
	  "\\tableofcontents\n\\newpage\n\\setcounter{page}{1}\n";
	
	return header;
}

void clean_stdin(){
    int c;
    do{
        c = getchar();
    } while (c != '\n' && c != EOF);
}

void help_info(){
	cout << "--html \t\t Convert to HTML\n"
	  "--latex\t\t Convert to Latex\n"
	  "--asciidoc \t Convert to Asciidoc\n"
	  "--markdown \t Convert to Markdown\n"
	  "--own-styles \t Avoid default CSS styles \n"
	  "--help \t\t Print this help text and exit \n"
	  "-o FILE  \t Use FILE as output filename\n"
	  "--output FILE"
		 << endl;
}

string get_styles(){
	string aux="\t<style>\n"
	"\t\ta {text-decoration:none;}\n"
	"\t\ttable {border-collapse: collapse;}\n"
	"\t\ttable, th, td {\n"
	"\t\t\tborder: 1px solid black;\n"
	"\t\t\tpadding: 15px;\n"
	"\t\t}\n"
	"\t\tth {height: 50px;}\n"
	"\t\th1,h2,h3{text-align:center;}\n"
	"\t\thtml{\n"
	"\t\t\tmargin-left:10%;\n"
	"\t\t\tbackground-color:#fff;\n"
	"\t\t\tfont-size:20px;\n"
	"\t\t\tfont-family:sans-serif;\n"
	"\t\t\tcolor:#000;\n"
	"\t\t}\n"
	"\t</style>\n";
	return aux;
}
